package com.jbinfo.qingcaowan.wx;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jbinfo.qingcaowan.common.BusinessException;
import com.jbinfo.qingcaowan.common.ExceptionConstants.BusinessExceptionCode;

import net.sf.json.JSONObject;

public class WxLogin {
	
	private static Logger log = LoggerFactory.getLogger(WxLogin.class);
	
//	private static String APPID = "wxae4ab6dc0bc46b2d";
//	private static String APP_SECRET= "904e7e5082ab163a355a08104e4377e0";
	private static String APPID = CommonURL.AppId;
	private static String APP_SECRET = CommonURL.AppSecret;
	
	private static String GET_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?grant_type=authorization_code";
//	https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
	private static String GET_USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo?lang=zh_CN";
	
	public WxInfo getTokenAndOpenId(WxInfo wxInfo) throws Exception {
		WxInfo wxRet = null;
		
		String code = wxInfo.getCode();
		
		if (wxInfo.getCode() == null || wxInfo.getCode().isEmpty()) {
			throw new BusinessException(BusinessExceptionCode.param_error, "code不能为空！");
			
		}
		// &appid=APPID&secret=SECRET&code=CODE
		String url = GET_TOKEN_URL + "&appid="+APPID+"&secret="+APP_SECRET+"&code="+code;
		
		JSONObject jsonObject = HttpCommonUtil.httpsRequest(url, "GET", null);
		
		log.info("getTokenAndOpenId jsonObject: " + jsonObject.toString());
		
		if (null != jsonObject) {
			wxRet = new WxInfo();
            if (jsonObject.getString("access_token") != null) {
    			wxRet.setAccess_token(jsonObject.getString("access_token"));
            }
            if (jsonObject.getString("expires_in") != null) {
            	wxRet.setExpires_in(jsonObject.getString("expires_in"));
            }
            if (jsonObject.getString("openid") != null) {
    			wxRet.setOpenId(jsonObject.getString("openid"));
            }
            if (jsonObject.getString("refresh_token") != null) {
    			wxRet.setRefresh_token(jsonObject.getString("refresh_token"));
            }
            if (jsonObject.getString("scope") != null) {
    			wxRet.setScope(jsonObject.getString("scope"));
            }
			if (jsonObject.has("unionid") && 
					jsonObject.getString("unionid") != null) {
				wxRet.setUnionid(jsonObject.getString("unionid"));
			}
			if (jsonObject.has("errcode") &&
					jsonObject.getString("errcode") != null) {
				
				wxRet = null;
	        	String errorCode = jsonObject.getString("errcode");
	            String errorMsg = jsonObject.getString("errmsg");
	            log.error("获取网页授权凭证失败 errcode:{} errmsg:{}", errorCode, errorMsg);
			}
		}
		
		return wxRet;
	}
	
	public WxUserInfo getUserInfo(WxInfo wxInfo) throws Exception {
		WxUserInfo wxUserDTO = null;
		
		String ACCESS_TOKEN = wxInfo.getAccess_token();
		String OPENID = wxInfo.getOpenId();
//		&access_token=ACCESS_TOKEN&openid=OPENID
		String url = GET_USERINFO_URL + "&access_token="+ACCESS_TOKEN+"&openid="+OPENID;
		
		JSONObject jsonObject = HttpCommonUtil.httpsRequest(url, "GET", null);
		
		if (null != jsonObject) {
        	wxUserDTO = new WxUserInfo();
        	if (jsonObject.getString("openid") != null) {
        		wxUserDTO.setOpenid(jsonObject.getString("openid"));
        	}
        	if (jsonObject.getString("nickname") != null) {
        		wxUserDTO.setNickname(jsonObject.getString("nickname"));
        	}
			if (jsonObject.getString("sex") != null) {
				wxUserDTO.setSex(jsonObject.getString("sex"));
			}
			if (jsonObject.getString("province") != null) {
				wxUserDTO.setProvince(jsonObject.getString("province"));
			}
			if (jsonObject.getString("city") != null) {
				wxUserDTO.setCity(jsonObject.getString("city"));
			}
			if (jsonObject.getString("country") != null) {
				wxUserDTO.setCountry(jsonObject.getString("country"));
			}
			if (jsonObject.getString("headimgurl") != null) {
				wxUserDTO.setHeadimgurl(jsonObject.getString("headimgurl"));
			}
			if (jsonObject.getString("privilege") != null) {
				wxUserDTO.setPrivilege(jsonObject.getString("privilege"));
			}
			
			if (jsonObject.has("unionid") && 
					jsonObject.getString("unionid") != null) {
				wxUserDTO.setUnionid(jsonObject.getString("unionid"));
			}
			
			if (jsonObject.has("errcode") && 
					jsonObject.getString("errcode") != null) {
				wxUserDTO = null;
				String errorCode = jsonObject.getString("errcode");
	            String errorMsg = jsonObject.getString("errmsg");
	            log.error("获取用户信息失败 errcode:{} errmsg:{}", errorCode, errorMsg);
			}
        }
		
		return wxUserDTO;
	}
}
